<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\cdc;

use app\command\BaseWork;
use app\enum\CdcEnum;
use app\model\CostTaskAccountCompareModel;
use app\model\CostTaskAccountModel;
use app\service\cdc\cost\flow\FlowInterface;
use app\service\cdc\cost\TaskAccountCompareService;
use app\service\cdc\cost\TaskAccountService;
use app\service\client\AccountService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class CostBeRecallCostTaskWork extends BaseWork
{
    /**
     * @var int 锁-有效时间
     */
    public const REDIS_LOCK_TTL = 30 * 60;

    /**
     * @var int 最大页数
     */
    public const MAX_PAGE = 50;

    /**
     * @var int 当前页数
     */
    public int $currPage = 0;

    protected function configure()
    {
        // 指令配置
        $this->setName('cost_be_recall_cost_task_work');
        // 设置参数
        $this->setDescription('生成拉取回溯任务')
            ->addArgument('task_type', Argument::REQUIRED, '任务类型  1：账户 2：视频  3：图片')
            ->addArgument('date_type', Argument::REQUIRED, '日期类型 1:今日  2:昨日')
            ->addArgument('media_id', Argument::OPTIONAL, '媒体id')
            ->addArgument('date', Argument::OPTIONAL, '日期 Ymd')
            ->setHelp('php think cost_be_recall_cost_task_work [task_type] [date_type] [media_id] [date]');
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $mediaId = intval($input->getArgument('media_id'));
        $taskType = intval($input->getArgument('task_type'));
        $dateType = $input->getArgument('date_type');
        if ($dateType == 1) {
            $dateInt = date('Ymd');
        } elseif ($dateType == 2) {
            $dateInt = date('Ymd', strtotime('-1 day'));
        } else {
            $dateInt = $input->getArgument('date') ?: date('Ymd', strtotime('-1 day'));
        }
        $dateInt = intval($dateInt);

        $this->getOutputMessage('生成拉取回溯任务开始');
        $service = TaskAccountService::getCostFlowService($taskType);
        if (! $service instanceof FlowInterface) {
            $this->getOutputMessage('服务类型未知');
            return false;
        }

        $where = [
            ['media_id', '=', $mediaId],
            ['new_stat_date', '<=', $dateInt],
            ['type', '=', $taskType],
            ['new_task_account_id', '=', 0],
            ['status', '=', CostTaskAccountCompareModel::STATUS_DISABLE],
        ];

        // 超过5min就停止
        $t = time();
        $runTime = 5 * 60;
        while (time() - $t <= $runTime) {
            (new CostTaskAccountCompareModel())->field(true)->where($where)->chunk(200, function ($items) use ($service) {
                if ($this->currPage > self::MAX_PAGE) {
                    return false;
                }

                try {
                    foreach ($items as $item) {
                        $this->getOutputMessage('id:' . $item->getkey() . '开始！');

                        // 加锁
                        $lockKey = sprintf(CdcEnum::CDC_TASK_LOCK, $item->getkey());

                        if (TaskAccountCompareService::lock($lockKey, 1, self::REDIS_LOCK_TTL)) {
                            $accountModel = AccountService::getAccountModel($item->getAttr('account_id'));
                            // todo 判断是否在投状态，如已停投，则不做处理，直接删除对比数据
                            $taskAccount = $service->setTaskAccountData($accountModel, intval($item->getAttr('stat_date')));
                            if (! $taskAccount instanceof CostTaskAccountModel) {
                                // 没有数据，删除对比数据
                                (new CostTaskAccountCompareModel())->where('id', $item->getKey())->delete();
                                $this->getOutputMessage('id:' . $item->getKey() . $service::getError(0));
                                return false;
                            }
                            $res = TaskAccountCompareService::updateCompareData($item, ['new_task_account_id' => $taskAccount->getKey()]);
                            if (! $res) {
                                $this->getOutputMessage('id:' . $item->getKey() . TaskAccountCompareService::getError(0));
                            }

                            $this->getOutputMessage('id:' . $item->getKey() . '结束！');
                        } else {
                            $this->getOutputMessage('redis锁未释放，id:' . $item->getKey());
                        }
                    }
                } catch (\Exception $e) {
                    $this->getOutputMessage($e->getMessage());
                }

                ++$this->currPage;
            });
            sleep(rand(5, 10));
        }
        $this->getOutputMessage('生成拉取回溯任务结束');
    }
}
